package org.future.task.redis.factory;

import org.future.task.core.handler.Connection;
import org.future.task.core.serialize.MineSerializer;
import org.future.task.redis.connection.RedisConnectionImpl;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import redis.clients.jedis.JedisPoolConfig;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author Chen-DW
 */
public class RedisTemplateFactory {


    public static CopyOnWriteArrayList<Connection> getRedisTemplate(List<String> hostAndPorts, JedisPoolConfig jedisPoolConfig, MineSerializer mineSerializer, int writeBatch, int localCacheSize, int commitThreadSize) throws IllegalAccessException, ClassNotFoundException, InstantiationException {
        CopyOnWriteArrayList<Connection> redisTemplates = new CopyOnWriteArrayList<>();
        for (String hostAndPort : hostAndPorts) {
            RedisTemplate<?, ?> redisTemplate = new RedisTemplate<>();
            redisTemplate.setConnectionFactory(getJedisFactory(hostAndPort, jedisPoolConfig));
            redisTemplate.afterPropertiesSet();
            RedisConnectionImpl redisConnection = new RedisConnectionImpl(redisTemplate, mineSerializer, writeBatch, localCacheSize, commitThreadSize);
            redisTemplates.add(redisConnection);
        }
        return redisTemplates;
    }

    private static JedisConnectionFactory getJedisFactory(String hostAndPort, JedisPoolConfig jedisPoolConfig) {

        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        String[] split = hostAndPort.split(":");
        redisStandaloneConfiguration.setHostName(split[0]);
        redisStandaloneConfiguration.setPort(Integer.parseInt(split[1]));
        if (split.length > 2) {
            String password = split[2];
            redisStandaloneConfiguration.setPassword(password);
        }
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(redisStandaloneConfiguration);
        if (jedisPoolConfig != null) {
            try {
                jedisConnectionFactory.setPoolConfig(jedisPoolConfig);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        jedisConnectionFactory.afterPropertiesSet();
        return jedisConnectionFactory;
    }
}
